package com.apes.fn.server.praticalFunction.model;

import com.apes.framework.jpa.DefaultPersistListener;
import com.apes.framework.jpa.Model;
import com.apes.framework.jpa.comment.Comment;
import com.apes.framework.jpa.generator.ApesGenerator;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SelectBeforeUpdate;

import javax.persistence.*;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by lishikun on 2021/6/11 10:08
 */
@Getter
@Setter
@SelectBeforeUpdate
@DynamicInsert
@DynamicUpdate
@Entity
@EntityListeners(DefaultPersistListener.class)
@Table(name = SmartAccessoriesConfig.CONST_TABLE_NAME)
public class SmartAccessoriesConfig extends Model {
    public static final String CONST_TABLE_NAME = "smart_accessories_config";

    @Id
    @Column(name = "id")
    @ApesGenerator(code = CONST_TABLE_NAME, name = "智选配件配置表", prefix="1",padding = 6)
    @Comment("编码")
    private String id;

    @Column(name = "plan_name")
    @Comment("方案名称")
    private String planName;

    @Column(name = "valid", nullable = false, columnDefinition = "number(1,0) default 1")
    @Comment("有效标记")
    private boolean valid = true; //有效

    @Column(name = "matching_product_config")
    @Comment("匹配商品列表配置")
    private int matchingProductConfig = 0;

    @Column(name = "smart_accessories_config")
    @Comment("智能配件列表配置")
    private int smartAccessoriesConfig = 0;

    @Column(name = "filter_condition", nullable = false, columnDefinition = "number(1,0) default 1")
    @Comment("筛选条件")
    private boolean filterCondition = true; //有效

    @Comment("适用品类")
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "smartAccessoriesConfig", orphanRemoval = true)
    private List<AdapterClassify> adapterCategories = new ArrayList<>();

    @Comment("商品过滤条件")
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "smartAccessoriesConfig", orphanRemoval = true)
    private List<CommodityExpandConfig> commodityExpandConfigs = new ArrayList<>();


    public List<AdapterClassify> getAdapterCategories() {
        if (adapterCategories == null) adapterCategories = new ArrayList();
        for (AdapterClassify adapterClassify : adapterCategories) {
            adapterClassify.setSmartAccessoriesConfig(this);
        }
        return adapterCategories;
    }

    public List<CommodityExpandConfig> getCommodityExpandConfigs() {
        if (adapterCategories == null) adapterCategories = new ArrayList();
        for (CommodityExpandConfig commodityExpandConfig : commodityExpandConfigs) {
            commodityExpandConfig.setSmartAccessoriesConfig(this);
        }
        return commodityExpandConfigs.stream().sorted(Comparator.comparing(commodityExpandConfig -> commodityExpandConfig.getSort())).collect(Collectors.toList());
    }
}
